import json

import numpy as np
import pandas as pd

from fof_model import FactorModelHelper


cfg = json.load(open("./model_config.json"))
model_helper = FactorModelHelper("./data")
model = model_helper.get_model(cfg)

portfolio = pd.read_csv("./portfolio.csv", converters={"code": str})
portfolio_exposure = {
    "alpha": 0.0,
    "mse": 0.0,
    "exposure": {x: 0.0 for x in model.factor_list},
}
for i in range(len(portfolio)):
    cur_line = portfolio.iloc[i]
    if cur_line.type == "stock":
        rtn = model_helper.returns_helper.get_stock_return(cur_line.code)
    cur_res = model.get_asset_exposure(rtn, alpha=True)
    print(cur_res)
    w = cur_line["weight"]
    portfolio_exposure["alpha"] += cur_res["alpha"] * w
    portfolio_exposure["mse"] += (cur_res["indivial_risk"] * w) ** 2
    for factor in model.factor_list:
        portfolio_exposure["exposure"][factor] += cur_res["exposure"][factor] * w
portfolio_exposure["indivial_risk"] = np.sqrt(portfolio_exposure["mse"])
del portfolio_exposure["mse"]

print("---------------------")
print(portfolio_exposure)
